import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class DioDemo extends StatelessWidget {
  const DioDemo({
    super.key,
    this.title = '',
    this.content = '',
    this.tColor = Colors.orange,
    this.cColor = Colors.yellow,
  });

  final String title;
  final String content;
  final Color tColor;
  final Color cColor;

  // 重写build 返回需要封装的组件即可
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.purple,
          title: Center(
            child: Text(
              '标题 $title',
              style: TextStyle(
                  color: tColor, fontSize: 30, fontWeight: FontWeight.w900),
            ),
          ),
        ),
        // 1.2 主体部分
        body: const Center(
          child: MyStateWidget(),
        ),
      ),
    );
  }
}

// 1. 继承自StatefulWidget
class MyStateWidget extends StatefulWidget {
  const MyStateWidget({super.key});
  @override
  // 创建组件时调用
  State<MyStateWidget> createState() {
    return _MyStateWidgetState();
  }
}

class _MyStateWidgetState extends State<MyStateWidget> {
  String joke = '正在加载笑话…………';
  @override
  // 组件被初始化时调用
  void initState() {
    super.initState();
    loadData();
  }

  final dio = Dio();

  loadData() async {
    // https://mock.boxuegu.com/mock/1172/orders
    final response = await dio.get('https://api-vue-base.itheima.net/api/joke');
    // ignore: avoid_print
    // print(response);
    setState(() {
      joke = response.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(
          joke,
          style: TextStyle(fontSize: 30),
        ),
        ElevatedButton(
          onPressed: () {
            setState(() {
              // 修改状态变量
              loadData();
            });
          },
          child: const Text('换一个'),
        ),
      ],
    );
  }
}
